import { Global } from "./../../Global/index";
/*
 * @Date: 2023-02-11 19:18:57
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-16 15:25:20
 * @FilePath: \A19\backend\src\api\Create\ApiCreateCourse.ts
 */
import { ApiCall } from "tsrpc";
import {
  ReqCreateCourse,
  ResCreateCourse,
} from "../../shared/protocols/Create/PtlCreateCourse";
import upload from "../../utils/upload";

export default async function (
  call: ApiCall<ReqCreateCourse, ResCreateCourse>
) {
  const teacher = call.currentUser;
  const { cover, name, introduction } = call.req;

  if (cover) {

    const {fileType,fileDate} = cover
    try {
      const index = fileType.indexOf("/");
      const typeCate = fileType.slice(0, index);
      const type = fileType.slice(index + 1);

      const ret = await upload(
        {
          folder: "covers",
          typeCate,
          type,
        },
        fileDate
      );

      const ins = {
        name,
        introduction,
        cover: ret,
        school: teacher.school,
        teacher: teacher._id,
        createdTime: new Date(),
      };

      const course = await Global.collection("courses").insertOne(ins);

      call.succ({
        course: {
          ...ins,
          _id: course.insertedId,
        },
      });
    } catch (error) {
      if (error instanceof Error) call.error(error.message);
    }
  }
  else{
    const ins = {
        name,
        introduction,
        cover: '/cover.jpg',
        school: teacher.school,
        teacher: teacher._id,
        createdTime: new Date(),
      };

    const course = await Global.collection("courses").insertOne(ins);

      call.succ({
        course: {
          ...ins,
          _id: course.insertedId,
        },
      });
  }
}
